package DAO.impl.hibernate;

import java.util.ArrayList;
import java.util.List;

import domain.User;
import DAO.IUserDAO;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Component
public class UserDaoImpl implements IUserDAO {

	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(UserDaoImpl.class);
	private SessionFactory sessionFactory;
		
	public UserDaoImpl() {}
	
	public UserDaoImpl(SessionFactory sessionFactory) {
		super();
		this.sessionFactory = sessionFactory;
	}
	

	@Override
	public boolean registerUser(User user) {			
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(user);				
		return true;	
	}

	@Override
	public User getUser(String userNickName, String userPassword) {			
		Session session = sessionFactory.getCurrentSession();			
		Query query = session.createQuery("from User q where q.userNickName=:name and q.userPassword=:password");	
		query.setString("name", userNickName);
		query.setString("password", userPassword);
		User user = (User) query.uniqueResult(); 	
		
		return user;	
	}

	public User getUser(int id) {
		Session session = sessionFactory.getCurrentSession();
		User user = (User)session.get(User.class, id);	
		return user;	
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {		
		List<User> users = new ArrayList<User>();
		Session session = sessionFactory.getCurrentSession();
		users = session.createQuery("from User").list();
		return users;	
	}
	
	@Override
	public boolean updateUserData(User user) {		
		return registerUser(user);
	}

	@Override
	public boolean deleteUser(int id) {		
		User user = getUser(id);				
		return deleteUser(user);	
	}
	
	public boolean deleteUser(User user) {
		boolean result = false;		
		Session session = sessionFactory.getCurrentSession();					
		if (user != null) {
			session.delete(user);
			result = true;
		}			
		return result;	
	}
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
